import store from '@/store'
import { EventBus } from '@/tools/bus'
import { wsSend } from "@/tools/sendMessage";

export const webSocketManger = {
  data() {
    return {
      ws: null,
      wsUrl: '',
      isConnect: false,
      isReconnect: false,
      reconnectCount: 0,
      reconnectTime: 3000,
      reconnectMaxCount: 5,
      reconnectTimer: null,
    }
  },
  mounted() {
    fetch('/static/ipConfig.json')
      .then(res => res.json())
      .then(data => {
        this.wsUrl = data.wsbaseUrl
        this.connect()
      })
      .catch(err => {
        console.error('加载配置文件失败:', err)
      })
  },
  methods: {
    connect() {
      if (!this.wsUrl) return
      if (this.ws) {
        this.ws.close()
        this.ws = null
      }
      this.ws = new WebSocket(this.wsUrl)

      this.ws.onopen = () => {
        console.log('WebSocket 连接成功',this.ws)
        this.$message.success('WebSocket 连接成功')
        store.commit('setWebSocket', this.ws)
        EventBus.$emit('ws-connected')
        this.isConnect = true
        this.isReconnect = false
        this.reconnectCount = 0

        wsSend({"cmd":"getLoginUserInfo"})
        if (this.reconnectTimer) {
          clearTimeout(this.reconnectTimer)
          this.reconnectTimer = null
        }
      }

      this.ws.onmessage = (event) => {
        const data=JSON.parse(event.data)
        console.log('收到消息:', data)
       if (data.cmd==='getLoginUserInfo'){
         store.commit('setUserInfo',data.data)
       }
       else {
         EventBus.$emit('ws-message', data)
       }
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误', error)
        this.$message.error('WebSocket 错误')
      }

      this.ws.onclose = () => {
        console.log('WebSocket 连接关闭')
        this.$message.error('WebSocket 连接关闭')
        this.isConnect = false
        store.commit('setWebSocket', null)
        EventBus.$emit('ws-close')

        if (!this.isReconnect && this.reconnectCount < this.reconnectMaxCount) {
          this.isReconnect = true
          this.reconnectTimer = setTimeout(() => {
            this.isReconnect = false
            this.reconnectCount++
            console.log(`第${this.reconnectCount}次重连`)
            this.$message.info(`第${this.reconnectCount}次重连`)
            this.connect()
          }, this.reconnectTime)
        }else{
          this.$message.error('已达到重连最大次数,请稍后再试')
        }
      }
    },

    close() {
      if (this.ws) {
        this.ws.close()
      }
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer)
        this.reconnectTimer = null
      }
      this.isConnect = false
      this.isReconnect = false
      this.reconnectCount = 0
      store.commit('setWebSocket',null)
    }
  }
}
